//
//  DeviceDetalVC.m
//  KEREN
//
//  Created by MW on 2023/4/6.
//

#import "DeviceDetalVC.h"
#import "DeviceDetailCell.h"
#import "KRTextCell.h"
#import "DeviceTransferenceVC.h"
@interface DeviceDetalVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *voucherArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, assign) int tactics_id;
@end

@implementation DeviceDetalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"车辆信息"];
    //TODO:国际化
    _titleArr = @[@"车辆型号",@"IMEI",@"SN",@"车架号",@"电机号",@"中控版本"];
    _voucherArr = @[@"购车网点",@"购车时间",@"激活时间",@"三包有效期",@"三包责任说明"];
    self.tableView.tableFooterView = [self footView];
    [self getDeviceinfo];
    
}

- (void)getDeviceinfo{
    WEAKSELF
    if([self.deviceInfo is4GDevice]){
        [NetworkingTool POST:Device_info parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                NSDictionary *dict = response[@"data"];
                [UserInfoManager sharedInstance].currentDeviceInfo = [DeviceInfo initWithDictionary:dict];
                [weakSelf getOtaCheckVersion];
                [weakSelf.tableView reloadData];
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {

        }];
    }else{
        CBPeripheralState state = [HABleManager checkBleConnectedState:self.deviceInfo.sn_code];
        if(state == CBPeripheralStateConnected){
            [HABleManager bleQueryDeviceSN:^(HABleModel * _Nonnull bleModel) {
                NSString *sn_code = [bleModel sn_code];
                [UserInfoManager sharedInstance].currentDeviceInfo.sn_code = sn_code;
                [weakSelf.tableView reloadData];
            }];
            [HABleManager bleQueryDeviceCharacteristic:^(HABleModel * _Nonnull bleModel) {
                NSString *imei = [bleModel imei];
                [UserInfoManager sharedInstance].currentDeviceInfo.imei = imei;
                [weakSelf.tableView reloadData];
            }];
            [HABleManager bleQueryDeviceOTAVersion:^(HABleModel * _Nonnull bleModel) {
                NSString *firmware_version = [bleModel firmware_version];
                DDLogInfo(@"======version is %@",firmware_version);
                [UserInfoManager sharedInstance].currentDeviceInfo.firmware_version = firmware_version;
                [weakSelf.tableView reloadData];
            }];
        }else{
            [[KRAlartManager shareInstance] showErrorAlert:@"蓝牙还未连上"];
        }
    }
}

- (void)getOtaCheckVersion{
    WEAKSELF
    if([UserInfoManager sharedInstance].currentDeviceInfo.sn_code.length > 0){
        NSDictionary *parameters = @{@"sn_code":[UserInfoManager sharedInstance].currentDeviceInfo.sn_code};
        [NetworkingTool POST:ota_checkVersion parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                if([response[@"data"] isKindOfClass:[NSDictionary class]]){
                    NSDictionary *dict = response[@"data"];
                    if([dict[@"release_type"] intValue] == 0){
                        if(dict[@"tactics_id"]){
                            weakSelf.tactics_id = [dict[@"tactics_id"] intValue];
                            [weakSelf.tableView reloadData];
                        }
                    }
                }
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return _titleArr.count;
    }else{
        return _voucherArr.count;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor clearColor];
    UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(24, 16, DEVICE_WIDTH - 50, 20)];
    if(section == 0){
        titleLbl.text = @"车辆信息";
    }else{
        titleLbl.text = @"三包凭证";
    }
    titleLbl.textColor = Color_86898E;
    titleLbl.font = Font(14);
    [headView addSubview:titleLbl];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        if(!_deviceInfo.deviceConfig.imei && indexPath.row == 1){
            return 0.01;
        }
        return 60;
    }else{
        if(indexPath.row == 4){
            return tableView.estimatedRowHeight;
        }
        return 60;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DeviceDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceDetailCell"];
    cell.decLbl.text = @"";
    [cell.scopyButton setImage:[UIImage imageNamed:@"device_detail_copy"] forState:UIControlStateNormal];
    cell.scopyButton.layer.cornerRadius = 16;
    cell.scopyButton.clipsToBounds = YES;
    cell.scopyButton.layer.borderWidth = 0;
    cell.cobtBtnWidthConstraint.constant = 32;
    if(indexPath.section == 0){
        if(indexPath.row == 0 || indexPath.row == 5){
            cell.scopyButton.hidden = YES;
            cell.decrightConstraint.constant = 24;
        }else{
            cell.scopyButton.hidden = NO;
            cell.decrightConstraint.constant = 50;
        }
        DeviceInfo *deviceInfo = [UserInfoManager sharedInstance].currentDeviceInfo;
        if(indexPath.row == 0){
            cell.decLbl.text = [deviceInfo is4GDevice] ? deviceInfo.type_name: deviceInfo.device_type_name;
        }else if(indexPath.row == 1){
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.imei;
            [cell.scopyButton addTarget:self action:@selector(copy:) forControlEvents:UIControlEventTouchUpInside];
        }else if (indexPath.row == 2){
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.sn_code;
            [cell.scopyButton addTarget:self action:@selector(copy:) forControlEvents:UIControlEventTouchUpInside];
        }else if (indexPath.row == 3){
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.frame_code;
            [cell.scopyButton addTarget:self action:@selector(copy:) forControlEvents:UIControlEventTouchUpInside];
        }else if (indexPath.row == 4){
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.engine_code;
            [cell.scopyButton addTarget:self action:@selector(copy:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            if(self.deviceInfo.deviceConfig.ota_upgrade && _tactics_id > 0){
                cell.scopyButton.hidden = NO;
                cell.decrightConstraint.constant = 76;
                cell.cobtBtnWidthConstraint.constant = 56;

                [cell.scopyButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.scopyButton setTitle:@"升级" forState:UIControlStateNormal];
                cell.scopyButton.titleLabel.font = BFont(16);
                cell.scopyButton.layer.borderColor = Color_7ACC00.CGColor;
                cell.scopyButton.layer.borderWidth = 1;
                [cell.scopyButton setTitleColor:Color_7ACC00 forState:UIControlStateNormal];
                [cell.scopyButton addTarget:self action:@selector(getOtaUpgrade) forControlEvents:UIControlEventTouchUpInside];
            }else{
                cell.scopyButton.hidden = YES;
                cell.decrightConstraint.constant = 24;
                cell.cobtBtnWidthConstraint.constant = 32;

            }
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.firmware_version;
        }
        cell.titleLbl.text = _titleArr[indexPath.row];
        cell.scopyButton.tag = indexPath.row;
    }else{
        if(indexPath.row == 4){
            KRTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRTextCell"];
            cell.titleLbl.text = _voucherArr[indexPath.row];
            cell.decLbl.text = @"为了切实保护消费者的合法权益，明确电动车设备销售者、修理者和生产者的修理、更换、退货（以下称“三包”）责任和义务，国家质检总局、国家工商总局、信息产业部联合发布第四号令，颁布了《电动车设备修理更换退货责任规定》。于2001年11月15日施行的《规定》共31条，消费者应当熟悉以下几点“三包”规定，以便更好的合理维护自身的合法权益。";
            return cell;
        }else{
            cell.scopyButton.hidden = YES;
            cell.decrightConstraint.constant = 24;
            cell.titleLbl.text = _voucherArr[indexPath.row];
        }
        if(indexPath.row == 0){
            //store_name
            cell.decLbl.text = [UserInfoManager sharedInstance].currentDeviceInfo.store_name;
        }else if (indexPath.row == 1){
            cell.decLbl.text = [[DeteManager shareInstance] timeFormatted:[UserInfoManager sharedInstance].currentDeviceInfo.buy_time];
        }else if (indexPath.row == 2){
            cell.decLbl.text = [[DeteManager shareInstance] timeFormatted:[UserInfoManager sharedInstance].currentDeviceInfo.activation_time];
        }else if (indexPath.row == 3){
            cell.decLbl.text = [NSString stringWithFormat:@"%@ 至 %@",[[DeteManager shareInstance] timeFormatYYYYMMdd:[UserInfoManager sharedInstance].currentDeviceInfo.buy_time], [[DeteManager shareInstance] timeFormatYYYYMMdd:[UserInfoManager sharedInstance].currentDeviceInfo.warranty_period_time]];
        }
    }
        return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)getOtaUpgrade{
    //ota_upgrade
    WEAKSELF
    NSDictionary *parameters = @{@"sn_code":[UserInfoManager sharedInstance].currentDeviceInfo.sn_code,@"status":@(1),@"tactics_id":@(_tactics_id)};
    [NetworkingTool POST:ota_upgrade_url parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            weakSelf.tactics_id = 0;
            [[KRAlartManager shareInstance] showAlert:@"设备升级中"];
            [weakSelf.tableView reloadData];
        }else{
            
        }

    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)copy:(UIButton *)sender{
    NSString *copyStr;
    if(sender.tag == 0){
        copyStr = [UserInfoManager sharedInstance].currentDeviceInfo.type_name;
    }else if(sender.tag == 1){
        copyStr = [UserInfoManager sharedInstance].currentDeviceInfo.imei;
    }else if (sender.tag == 2){
        copyStr = [UserInfoManager sharedInstance].currentDeviceInfo.sn_code;
    }else if (sender.tag == 3){
        copyStr = [UserInfoManager sharedInstance].currentDeviceInfo.frame_code;
    }else if (sender.tag == 4){
        copyStr = [UserInfoManager sharedInstance].currentDeviceInfo.engine_code;
    }
    UIPasteboard *pad = [UIPasteboard generalPasteboard];
    pad.string = copyStr;

    [[KRAlartManager shareInstance] showAlert:@"复制成功"];
}

- (void)unbindClick{
    if(![UserInfoManager sharedInstance].currentDeviceInfo.is_manager){
        [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        return;
    }
    [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"确定解除绑定吗？" decTitle:@"车辆信息、行程，订单，轨迹，行车记录信息支持保存一年，过期后数据会自动删除。" cancleBtnText:@"取消" andOkBtnText:@"确认" sucessBlock:^(BOOL isSucess) {
        if(isSucess){
            [self unbind];
        }
    }];
}

- (void)unbind{
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    WEAKSELF
    NSDictionary *parameters = @{@"sn_code":[UserInfoManager sharedInstance].currentDeviceInfo.sn_code,@"id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id)};
    [NetworkingTool POST:Device_unbind parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [[HABleManager sharedManager] cancelConnectToPeripheral:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
                            
            }];
            [[KRAlartManager shareInstance] hidenAlartView];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }else{
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}
- (void)transference{
    if(![UserInfoManager sharedInstance].currentDeviceInfo.is_manager){
        [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        return;
    }
    DeviceTransferenceVC *vc = [[DeviceTransferenceVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DeviceDetailCell" bundle:nil] forCellReuseIdentifier:@"DeviceDetailCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"KRTextCell" bundle:nil] forCellReuseIdentifier:@"KRTextCell"];
    
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UIView *)footView{
    if(!_footView){
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 150)];
        _footView.backgroundColor = [UIColor clearColor];
        UIButton *unbind = [UIButton setButtonWithTitle:@"解除绑定" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
        [_footView addSubview:unbind];
        [unbind mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.offset((DEVICE_WIDTH - 48 - 10) /2);
            make.height.offset(48);
            make.top.offset(40);
        }];
        [unbind addTarget:self action:@selector(unbindClick) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *transferenceBtn = [UIButton setButtonWithTitle:@"授权转让" titleColor:Color_7ACC00 titleFont:BFont(16) cornerRadius:25 backColor:Whire_Color];
        [_footView addSubview:transferenceBtn];
        [transferenceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-24);
            make.width.offset((DEVICE_WIDTH - 48 - 10) / 2);
            make.height.offset(48);
            make.top.offset(40);
        }];
        [transferenceBtn addTarget:self action:@selector(transference) forControlEvents:UIControlEventTouchUpInside];


    }
    return _footView;
}



@end
